package BIOThread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOServer {

    public static void main(String[] args) {
        // 使用socket 进行网络通信
        try {
            ServerSocket serverSocket = new ServerSocket(8000);
            System.out.println("服务端启动成功， 监听端口为8000， 等待客户端连接");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功，客户信息为" + serverSocket.getInetAddress());
                // 针对每一个连接创建一个线程， 去处理IO操作
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // 基于字节流
                            InputStream in = socket.getInputStream();
                            byte[] buffer = new byte[1024];
                            int len = 0;
                            // 读取客户端的数据
                            while ((len = in.read(buffer)) > 0) {
                                System.out.println(new String(buffer, 0, len));
                            }
                            // 向客户端写数据
                            OutputStream out = socket.getOutputStream();
                            out.write("hello!".getBytes());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}